package com.video4s.parser;

import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.video4s.entity.UserYoutubeEntity;
import com.video4s.entity.VideoEntity;
import com.video4s.manager.ManagerQueue;

public class Youtube {
	private static Logger logger = Logger.getLogger(Youtube.class);

	private void getMoreVideo(String url, UserYoutubeEntity userYoutubeEntity) {
		try {
			if (!url.equals("http://www.youtube.com")) {
				URL oracle = new URL(url);
				URLConnection connection = oracle.openConnection();
				connection
						.addRequestProperty(
								"User-Agent",
								"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
				Document doc = Jsoup.parse(connection.getInputStream(),
						"UTF-8", "application/json; charset=UTF-8");
				Elements els = doc.select("body");
				JSONObject jsonObject = JSONObject.fromObject(els.text());

				Document docParse = Jsoup.parse(jsonObject.get("content_html")
						.toString());
				Elements elsParse = docParse
						.select("a[href*=/watch?v]:has(img)");

				Document docLinkMore = Jsoup.parse(jsonObject.get(
						"load_more_widget_html").toString());
				Elements elsButton = docLinkMore
						.select("button[data-uix-load-more-href]");
				String linkMore = "http://www.youtube.com"
						+ elsButton.attr("data-uix-load-more-href").trim();
				getListChilrent(elsParse, userYoutubeEntity);
				getMoreVideo(linkMore, userYoutubeEntity);
			}
		} catch (Exception e) {
			logger.info("## ERROR GET MORE: " + e.getMessage());
		}

	}

	private String[] getTitleAndDescription(String url) throws Exception {

		String[] str = new String[2];

		Document doc = Jsoup
				.connect(url)
				.userAgent(
						"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31")
				.get();
		Elements els = doc.select("meta[name=description]");
		str[0] = new String(doc.title().trim());
		str[1] = new String(els.attr("content").trim());

		return str;
	}

	private void getListChilrent(Elements els,UserYoutubeEntity userYoutubeEntity)
			throws Exception {
		for (Element element : els) {
			if (element.attr("href").contains("list=")) {
				continue;
			}
			String link = "http://www.youtube.com" + element.attr("href");
			String img = "";
			String title = "";
			String[] titleDesctiption = new String[2];
			try {
				titleDesctiption = getTitleAndDescription(link);
			} catch (Exception e) {
				logger.info("## ERROR LINK: " + link,e);
				titleDesctiption[0] = new String();
				titleDesctiption[1] = new String();
			}
			
			String description = titleDesctiption[1];
			if (element.select("img").attr("data-thumb").trim().equals("")) {
				img = element.select("img").attr("src");
			} else {
				img = element.select("img").attr("data-thumb");
			}
			if (element.select("span.title").attr("title").trim().equals("")) {
				title = titleDesctiption[0].replaceAll("- YouTube", "");
			} else {
				title = element.select("span.title").attr("title").trim();
			}

			VideoEntity youtubeEntity = new VideoEntity();
			youtubeEntity.setVideoFile(link.trim());
			youtubeEntity.setVideoImage(img.trim());
			youtubeEntity.setVideoTitle(title.trim());
			youtubeEntity.setVideoDescription(description.trim());
			youtubeEntity.setVideoResource(link.trim());
			youtubeEntity.setUserYoutubeId(userYoutubeEntity.getUserYoutubeId());
			youtubeEntity.setCategoryId(userYoutubeEntity.getCategoryId());
//			logger.info("## YOUTUBE ID: " + userYoutubeEntity.getUserYoutubeId());
//			logger.info("## YOUTUBE LINK :" + link);
//			logger.info("##################################################");
			ManagerQueue.concurrentLinkedQueueVideo.add(youtubeEntity);
		}

	}

	public void getListYou(UserYoutubeEntity youtubeEntity) throws Exception {

		Document doc = Jsoup
				.connect(youtubeEntity.getUserYoutubeLink())
				.userAgent(
						"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31")
				.get();
		Elements els = doc.select("a[href*=/watch?v]:has(img)");

		Elements elsButton = doc.select("button[data-uix-load-more-href]");
		String linkMore = "http://www.youtube.com"
				+ elsButton.attr("data-uix-load-more-href").trim();
		// System.out.println("Link more: " + linkMore);
		Elements elsUser = doc
				.select("a[href~=/(user|channel)/\\w+(/videos)?$]");
		for (Element element : elsUser) {
			String linkUser;
			if (element.attr("href").trim()
					.matches("/(user|channel)/\\w+/videos$")) {
				linkUser = "http://www.youtube.com"
						+ element.attr("href").trim();
			} else {
				linkUser = "http://www.youtube.com"
						+ element.attr("href").trim() + "/videos";
			}

			UserYoutubeEntity userYoutubeEntity = new UserYoutubeEntity();
			userYoutubeEntity.setCategoryId(0);
			userYoutubeEntity.setUserYoutubeId(UUID.randomUUID().toString());
			userYoutubeEntity.setUserYoutubeProcess(0);
			userYoutubeEntity.setUserYoutubeStatus(0);
			userYoutubeEntity.setUserYoutubeLink(linkUser.trim());
			ManagerQueue.concurrentLinkedQueueUserYoutube
					.add(userYoutubeEntity);
		}
		getListChilrent(els, youtubeEntity);
		getMoreVideo(linkMore, youtubeEntity);
	}
	
	public static void main(String[] args) {
		UserYoutubeEntity userYoutubeEntity = new UserYoutubeEntity();
		userYoutubeEntity.setUserYoutubeLink("http://www.youtube.com/user/LadyGagaVEVO/videos");
		try {
			new Youtube().getListYou(userYoutubeEntity);
			System.out.println(ManagerQueue.concurrentLinkedQueueVideo.size());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
